package day11;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//测试读写锁
public class TestReadWrite {
    Object data;//数据
    ReentrantReadWriteLock rrwlock = new ReentrantReadWriteLock(true);

    public void read() {
        try {
            String name = Thread.currentThread().getName();
            rrwlock.readLock().lock();
            System.out.println(name + "开始读取2S数据:" + data);
            Thread.sleep(2000);
            System.out.println(name + "结束读取2S数据:" + data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rrwlock.readLock().unlock();
        }
    }

    public void write(Object data) {
        try {
            String name = Thread.currentThread().getName();
            rrwlock.writeLock().lock();
            System.out.println(name + "开始写入2S数据:" + data);
            Thread.sleep(2000);
            this.data = data;
            System.out.println(name + "结束写入2S数据:" + data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rrwlock.writeLock().unlock();
        }
    }

    public static void main(String[] args) {
        TestReadWrite trw = new TestReadWrite();
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    trw.read();
                }
            }, "读取:" + i).start();
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    trw.write(System.currentTimeMillis());
                }
            }, "写入:" + i).start();
        }
    }

}
